package cn.tedu.v4;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * 多人聊天室 Version 4
 *
 */
public class Client {
    //优化 ②：动态数据全部私有化属性到类上--方便修改
    private static  String HOST="127.0.0.1";
    private static  int PORT=0202;
    private Socket socket;
    private String ip;
    //1.置空流 升级 Java00P 封装--私有化属性：本类任意地方都可以使用
    private PrintWriter pw;
    private BufferedReader br;


    public Client() {
        try {//172.20.12.31
            //私有化socket --拨通服务器电话--返回socket【不能省】
            socket = new Socket(HOST, PORT);
            ip=socket.getInetAddress().getHostAddress();
            br=new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
            pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF8")),true);
        }catch (UnknownHostException e){ //用户地址出问题异常
            System.out.println("IP地址有问题，请询问服务器端！");
        }catch (IOException e) { //IO异常：连接失效
            System.out.println("客户端主动退出了，断开连接");
        }


    }
    public void start()  {
        try {
            new Thread(()->{
                try {
                    String message;
                    while ((message=br.readLine())!=null){
                        System.out.println("服务器说:"+message);
                        System.out.print("客户端请输入");
                    }
                } catch (IOException e) {
                    System.out.println("服务器端发来的消息断开了");
                }
            }).start();

            Scanner input=new Scanner(System.in);
            while (true){
                System.out.println("客户端请输入:");
                String say=input.nextLine();
                pw.println(ip+"客户端说："+say);

            }
        } finally {
            if (pw!=null)
                pw.close();
            if (br!=null)
                try {
                    br.close();
                } catch (IOException e) {
                    System.out.println("服务器通讯内容失败");
                }
            if(socket!=null&&!socket.isClosed()){
                System.out.println("客户端关闭成功");
                try {
                    socket.close();
                } catch (IOException e) {
                    System.out.println("客户端关闭失败");
                }

            }
        }
    }

    public static void main(String[] args)  {
        new Client().start();
    }

}